<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use app\common\model\Precept as PreceptModel;
use app\common\model\User;
use app\common\model\PreceptOrder;
use app\common\model\PreceptEvaluate;
use think\exception\ValidateException;

class Precept extends Base
{
    /**
     * 添加方案
     */
    public function save()
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Precept');
            return Result::fastReturn(PreceptModel::add($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 处理方案
     */
    public function edit()
    {

        $param = $this->request->post();
        try {
            $this->validate($param, 'PreceptEdit');
            return Result::fastReturn(PreceptModel::edit($param, $this->user));
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 方案详情
     */
    public function info($id)
    {
        $info = PreceptModel::where('id', $id)->append(['statusText', 'typeText', 'typeTitle'])->with(['user', 'admin', 'huser', 'tuser'])->find();
        if (empty($info)) {
            return Result::fail('方案不存在');
        }
        $info->status_title = getPreceptFriendly($info->status);
        if($info->status == 2 && $this->user->level_id<=2){
            $info->status_title = '已认领 正在填写方案';
        }
        $pay = PreceptOrder::where(['precept_id' => $id, 'pay_state' => 1])->field('pay_time,pay_way,discount,real_price')->find();
        $info->admin->photo = '/static/api/img/photo.png';
        $info->admin->level->sub_title = '运营';
        $roles = [
            'id' => 1,
            'title' => '经理'
        ];
        $info->admin->role = $roles;
        $info->mobile = encryptPhone($info->tel);
        $info->user->mobile = encryptPhone($info->user->mobile);
        $info->pay_time = '';
        $info->discount = '';
        $info->real_price = '';
        $info->pay_way = '';
        if (!empty($pay)) {
            $info->pay_time = $pay->pay_time;
            $info->discount = $pay->discount;
            $info->real_price = $pay->real_price;
            $info->pay_way = $pay->pay_way;
        }
        return Result::success('获取成功！', $info);
    }
    /**
     * 方案列表
     */
    public function getList()
    {
        try {
            $param = $this->request->get();
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            $map[] = ['uid', '=', $this->user->id];
            $list = PreceptModel::getPageList($map, 'id,uid,h_id,rname,tel,status,type,price', $param['page'], 20, false, ['user', 'huser'], [], [], [], [], '', ['statusText', 'typeText']);
            foreach ($list['data'] as &$v) {
                $v->tel = encryptPhone($v->tel);
                $v->user->mobile = encryptPhone($v->user->mobile);
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 健康管理师
     */
    public function getHealthList()
    {
        try {
            $param = $this->request->get();
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            $map[] = ['h_id', '=', $this->user->id];
            $list = PreceptModel::getPageList($map, 'id,uid,h_id,rname,tel,status,type,price', $param['page'], 20, false, ['user', 'huser'], [], [], [], [], '', ['statusText', 'typeText']);
            foreach ($list['data'] as &$v) {
                $v->tel = encryptPhone($v->tel);
                $v->user->mobile = encryptPhone($v->user->mobile);
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 专家/服务团队
     */
    public function getTeamList()
    {
        try {
            $param = $this->request->get();
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
            $map[] = ['t_id', '=', $this->user->id];
            $list = PreceptModel::getPageList($map, 'id,uid,h_id,rname,tel,status,type,price', $param['page'], 20, false, ['user', 'huser'], [], [], [], [], '', ['statusText', 'typeText']);
            foreach ($list['data'] as &$v) {
                $v->tel = encryptPhone($v->tel);
                $v->user->mobile = encryptPhone($v->user->mobile);
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取需求
     */
    public function getTypeList()
    {
        try {
            return Result::success('获取成功', PreceptModel::getTypeList());
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取支付信息
     */
    public function getPayInfo($id)
    {
        try {
            $info = PreceptModel::where(['id' => $id, 'uid' => $this->user->id])->field('id,rname,tel,h_id,price,type')->append(['typeText'])->with(['huser'])->find();
            if (empty($info)) {
                return Result::fail('方案不存在');
            }
            $info->tel = encryptPhone($info->tel);
            $info->huser->mobile = encryptPhone($info->huser->mobile);
            $info->pay_list = \app\common\model\OrderTemporary::getPaymentMethod('currency,wechat', $this->user);
            $info->commission = $this->user->assets->bonus;
            $info->max_commission = round((\app\common\controller\Config::lists()['d_discount'] * $info->price), 2);
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 支付方案
     */
    public function pay()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(PreceptOrder::pay($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     *用户方案驳回
     */
    public function reject()
    {
        try {
            $param = $this->request->post();
            return Result::fastReturn(PreceptModel::reject($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取用户管理
     */
    public function getUserList()
    {
        try {
            $param = $this->request->get();
            if ($this->user->level_id == 1) {
                return Result::fail('参数错误');
            }
            if ($this->user->level_id == 2) {
                $uid = 'h_id';
            } else if ($this->user->level_id > 2) {
                $uid = 't_id';
            }
            $ulist = PreceptModel::where($uid, '=', $this->user->id)->column('uid');
            $map[] = ['id', 'in', $ulist];
            $list = User::getPageList($map, 'id,code,nickname,mobile,photo', $param['page'], 20, false);
            foreach ($list['data'] as &$v) {
                $v->mobile = encryptPhone($v->mobile);
            }
            return Result::fastReturn($list);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 数据统计
     */
    public function statistics()
    {
        try {
            $param = $this->request->get();
            if ($this->user->level_id == 1) {
                return Result::fail('参数错误');
            }
            if ($this->user->level_id == 2) {
                $uid = 'h_id';
            } else if ($this->user->level_id > 2) {
                $uid = 't_id';
            }
            $map[] = [$uid, '=', $this->user->id];
            $count = PreceptModel::where($map)->count();
            $count_day = PreceptModel::where($map)->whereDay('create_time')->count();
            $count_month = PreceptModel::where($map)->whereMonth('create_time')->count();
            $count_year = PreceptModel::where($map)->whereYear('create_time')->count();
            return Result::success('获取成功！', ['count' => $count, 'count_day' => $count_day, 'count_month' => $count_month, 'count_year' => $count_year]);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 获取曲线图数据
     */
    public function getCurve()
    {
        try {
            $param = $this->request->get();
            $start = $param['start'];
            $end = $param['end'];
            $date = 'Y-m-d';
            if ($end < $start) {
                return Result::fail('开始时间不能大于结束时间');
            }
            $ss = 1;
            if ((($end - $start) / 86400) >= 30) {
                $interval = 'P15D';
            } else if ($end == $start) {
                $interval = 'PT2H';
                $date = 'Y-m-d H:i';
                $end = $param['end'] + 86400;
                $ss = 2;
            } else {
                $interval = 'P1D';
            }
            if ($this->user->level_id == 1) {
                return Result::fail('参数错误');
            }
            if ($this->user->level_id == 2) {
                $uid = 'h_id';
            } else if ($this->user->level_id > 2) {
                $uid = 't_id';
            }
            $map[] = [$uid, '=', $this->user->id];
            $list =  getTimePointsBetween(date('Y-m-d', intval($start)), date('Y-m-d', intval($end)), $interval, $date);
            foreach ($list as $k => $v) {
                $vstart = strtotime($v);
                $x[] = $ss == 2 ? date('d H:i', strtotime($v)) : $v;
                if ($k == (count($list) - 1)) {
                    $info = PreceptModel::where($map)->where('create_time', '>=', $vstart)->count();
                } else {
                    $vend = strtotime($list[$k + 1]);
                    $info = PreceptModel::where($map)->where('create_time', '>=', $vstart)->where('create_time', '<', $vend)->count();
                }
                $y[] = $info;
            }
            $data['x'] = $x;
            $data['y'] = $y;
            $count = PreceptModel::where($map)->where('create_time', '>=', $start)->where('create_time', '<', $end)->count();
            $data['count'] = $count;
            return Result::success('获取成功！', $data);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * 获取评价内容
     */
    public function getComment()
    {
        try {
            $info = PreceptEvaluate::getComment();
            return Result::success('获取成功！', $info);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
    /**
     * 提交评价
     */
    public function submitEvaluate()
    {
        try {
            $param = $this->request->param();
            return Result::fastReturn(PreceptEvaluate::submit($param, $this->user));
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }
}
